package com.zmj.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.zmj.common.ResponseVO;
import com.zmj.dto.req.LoginReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Response;

/**
 * sa-token演示类
 *
 * @author zmj
 * @date 2021-11-10 11:07
 */
@Slf4j
@RestController
@RequestMapping("user/")
public class UserController {

    // 测试登录，浏览器访问：
    @RequestMapping("doLogin")
    public ResponseVO doLogin(LoginReq loginReq) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if ("zhang".equals(loginReq.getUsername()) && "123456".equals(loginReq.getPassword())) {
            StpUtil.login(10001);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return ResponseVO.build(tokenInfo);
        }
        return ResponseVO.error("用户名密码错误！");
    }

    // 查询登录状态
    @RequestMapping("isLogin")
    public ResponseVO isLogin() {
        return ResponseVO.build("当前会话是否登录：" + StpUtil.isLogin());
    }

    @RequestMapping("tokenInfo")
    public ResponseVO tokenInfo(String tokenValue) {
        String loginId = (String) StpUtil.getLoginIdByToken(tokenValue);
        log.info("用户id：【{}】", loginId);
        return ResponseVO.build(StpUtil.getTokenInfo());
    }

    @RequestMapping("loginOut")
    public ResponseVO loginOut() {
        StpUtil.logout();
        return ResponseVO.build();
    }


}
